package com.briup.ch10;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/14
 * @Description:
 */
//店员
class Clerk{
    //管理资源：成员变量、成员方法（生产、消费、通信、锁）
    //成员变量productCount：产品数 0
    protected int productCount=0;
    //生产产品，进货：produceProduct()
    public int produceProduct() {
        //如果小于20个，就生产，通知消费者notifyAll
        // 如果大于20个就等待
        synchronized(this){
            while(productCount>=20){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            productCount++;
            notifyAll();
        }
        return 1;
    }
    //消费产品，卖货：consumerProduct()
    public int consumerProduct() {
        //如果产品大于0，就消费，通知生产者notifyAll
        // 如果小于等于0，就等待
        synchronized(this){
            while(productCount<=0){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            productCount--;
            notifyAll();
        }
        return 1;
    }


}
//生产者 extends/implement 线程
class Producer extends  Thread{
    private final Clerk clerk;

    //店员对象  使用关系
    //构造器：线程名称，店员对象
    public Producer(String name,Clerk clerk){
        super(name);
        this.clerk=clerk;
    }
    //重写run

    @Override
    public void run() {
        //循环{ 每隔100毫秒就生产货物：店员对象.produceProduct()}
        while(true){
            try {
                Thread.sleep(100);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.produceProduct();
            System.out.println(Thread.currentThread().getName()+"生产了1个产品");

        }
    }


}

//消费者 线程
class Customer extends Thread{
    private final Clerk clerk;

    //店员对象  使用关系
    //构造器：线程名称，店员对象
    public Customer(String name,Clerk clerk){
        super(name);
        this.clerk=clerk;
    }
    //重写run
    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consumerProduct();
            System.out.println(Thread.currentThread().getName()+"消费了1个产品");
    }
    }
}
//测试类
public class Test24 {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producer p1 = new Producer("一号生产线", clerk);
        Producer p2 = new Producer("二号生产线", clerk);
        Customer c1 = new Customer("消费者1", clerk);
        Customer c2 = new Customer("消费者2", clerk);
        Customer c3 = new Customer("消费者3", clerk);
        Customer c4 = new Customer("消费者4", clerk);
        p1.start();
        p2.start();
        c1.start();
        c2.start();
        c3.start();
        c4.start();
    }
}
